import * as React from 'react';

import { WebsocketContext } from './context';
import WebSocketManager from './WebsocketManager';

export interface IWebSocketProviderProps {
  url: string;
  protocols?: string | string[];
  onOpen?: (ev: Event) => void;
  children: React.ReactNode;
}

export const WebSocketProvider: React.FC<IWebSocketProviderProps> = ({
  url,
  protocols,
  children,
  onOpen,
}) => {
  const ws = React.useRef<WebSocket | null>(null);
  const onOpenRef = React.useRef<(ev: Event) => void>();

  React.useEffect(() => {
    if (typeof window !== 'undefined') {
      try {
        ws.current = WebSocketManager.getInstance(url, protocols);
        ws.current.onclose = () => {
          console.log('websocket closed');
        };

        if (onOpen) {
          ws.current.onopen = onOpen;
        }
      } catch (error) {
        console.error(error);
      }
    }

    return () => {
      WebSocketManager.closeInstance();
    };
  }, [url, protocols, onOpen]);

  // 如果不在浏览器环境，直接返回 children
  if (typeof window === 'undefined') {
    return children;
  }

  return <WebsocketContext.Provider value={ws.current!}>{children}</WebsocketContext.Provider>;
};
